//
//  SYApiManager.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2020/8/11.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import Foundation
import Moya
import HandyJSON
import RxSwift



let ApiManagerProvider = MoyaProvider<SYApiManager>(endpointClosure: endpointMapping, requestClosure: requestTimeoutClosure, plugins:[])

public func endpointMapping<Target: TargetType>(target: Target) -> Endpoint {
    print("\n************************************************** separate *********************************************\n\n请求链接：\(target.baseURL)\(target.path) \n方法：\(target.method.rawValue) \n请求头：\(target.headers ?? [:])\n参数：\(String(describing: target.task.self))")
    //在这里设置你的HTTP头部信息
    return MoyaProvider.defaultEndpointMapping(for: target).adding(newHTTPHeaderFields: target.headers ?? [:])
}

//设置请求超时时间
private let requestTimeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<SYApiManager>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 60
        done(.success(request))
    } catch {
        return
    }
}

enum SYApiManager {
    
    case materialInfo(code: String)
}

extension SYApiManager: TargetType {
    
    var headers: [String : String]? {
        let token: String = UserDefaults.standard.value(forKey: "token") as! String
        return ["token": token, "Authorization": token]
    }
    
    var baseURL: URL {
        switch self {
        default:
            return URL(string: IP+VERSION)!
        }
    }
    
    var path: String {
        switch self {
            
        case .materialInfo(let code): return  String(format: "%@/%@", MATERIAL_INFO_UP, code)
        }
    }
    
    var method: Moya.Method {
        switch self {

        default:
            return .get
        }
    }
    
    var task: Task {
        switch self {
            
        default:
            return .requestPlain
        }
    }
    
    var validate: Bool {
        return false
    }
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
 
}



// MARK: 取消所有请求
func cancelAllRequest() {
    //    ApiManagerProvider.manager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
    //        dataTasks.forEach { $0.cancel() }
    //        uploadTasks.forEach { $0.cancel() }
    //        downloadTasks.forEach { $0.cancel() }
    //    }
    //
    //    ApiManagerProvider.manager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
    //        dataTasks.forEach { $0.cancel() }
    //        uploadTasks.forEach { $0.cancel() }
    //        downloadTasks.forEach { $0.cancel() }
    //    }
}


